// components/uploader-crad/uploader-crad.js
import toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
import { getOssToken ,updateAvatar } from "../../server/uploader"
import {back, getUserInfo} from "../../utils/login"
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },
  options: {
    styleIsolation: 'shared'
  },

  /**
   * 组件的初始数据
   */
  data: {
    fileList: [],
    key:""
  },

  /**
   * 组件的方法列表
   */
  methods: {
    afterRead(event) {
      const { file } = event.detail;
      // console.log(file);
      getOssToken().then(res => {
        // console.log(res);
        let { accessid, host, policy, signature } = res
        let key = "uploader" + file.url.slice(11)
        // console.log(key);
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        wx.uploadFile({
          url: host, // 仅为示例，非真实的接口地址
          filePath: file.url,
          name: 'file',
          formData: {
            key,
            policy,
            OSSAccessKeyId: accessid,
            signature,
          },
          success: (res) => {
            if (res.statusCode === 204) {
              // console.log('上传成功')
              // 上传完成需要更新 fileList
              wx.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 2000
              })
              const { fileList = [] } = this.data;
              fileList.push({ ...file });
              this.setData({ fileList ,key});
              // console.log(this.data.key);
            }
          },
          fail: err => {
            console.log(err);
          }
        });
      })

    },
    beforeRead(event) {
      const { file, callback } = event.detail;
      callback(file.type === 'image');
    },
    deleteFile(e) {
      // console.log(e.detail.index);
      let getFileList = this.data.fileList;
      getFileList.splice(e.detail.index, 1)
      this.setData({
        fileList: getFileList
      })
      // console.log(this.data.fileList);
    },
    FileOverSize(){
      wx.showToast({
        title: '上传文件太大',
        icon:"error",
        duration: 2000
      })
    },
    updateUserinfo(){
      if(this.data.key){
        updateAvatar({avatar:this.data.key}).then(res => {
          // console.log(res);
          getUserInfo().then(
            toast({
              type:"success",
              message: "修改成功",
              onClose: () => {
                back()
              }
            })
          )
        })
      }else{
        toast({
          type:"fail",
          message: "请先选择图片"
        })
      }
      
    }
  },
  
})
